<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\middleware;

class EncryptDemoDataMiddleware
{

    // 需要过滤的接口
    protected $demoRouteNeedEncrypt = [
        // 系统配置
        'v1.setting.config.SystemConfigController/listSystemConfig',
    ];

    // 需要脱敏字段
    protected $demoParamsNeedEncrypt = ['huoAccessKey', 'huoSecretKey', 'giteeClientId', 'giteeClientSecret'];

    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        // 非需校验的接口或者未开启演示模式放行
        $action = $request->controller() . '/' . $request->action();
        if (!in_array($action, $this->demoRouteNeedEncrypt) || env('env') != 'demo') {
            return $response;
        }

        // 非json数据
        if (!method_exists($response, 'header') || !in_array('application/json; charset=utf-8', $response->getHeader())) {
            return $response;
        }

        $data = $response->getData();
        if (!is_array($data) || empty($data)) {
            return $response;
        }

        foreach ($data['data'] as $key => $item) {

            // 字符串
            if (is_string($item)) {
                $data['data'][$key] = $this->getEncryptData($key, $item);
                continue;
            }

            // 数组
            if (is_array($item)) {
                foreach ($item as $itemKey => $itemValue) {
                    $data['data'][$key][$itemKey] = $this->getEncryptData($itemKey, $itemValue);
                }
            }
        }

        return $response->data($data);
    }

    protected function getEncryptData($key, $value)
    {
        // 隐藏字段
        if (in_array($key, $this->demoParamsNeedEncrypt)) {
            return '******';
        }

        return $value;
    }
}